from lib.settings import BTCC_API_URL
import time
import re
import hmac
import hashlib
import base64
import http.client
import urllib.request
import json


def get_tonce():
    return int(time.time() * 1000000)


def get_params_hash(pdict, secret_key):
    pstring = ""
    # The order of params is critical for calculating a correct hash
    fields = ['tonce', 'accesskey', 'requestmethod', 'id', 'method', 'params']
    for f in fields:
        if pdict[f]:
            if f == 'params':
                # Convert list to string, then strip brackets and spaces
                # probably a cleaner way to do this
                param_string = re.sub("[\[\] ]", "", str(pdict[f]))
                param_string = re.sub("'", '', param_string)
                param_string = re.sub("True", '1', param_string)
                param_string = re.sub("False", '', param_string)
                param_string = re.sub("None", '', param_string)
                pstring += f + '=' + param_string + '&'
            else:
                pstring += f + '=' + str(pdict[f]) + '&'
        else:
            pstring += f + '=&'
    pstring = pstring.strip('&')

    # now with correctly ordered param string, calculate hash
    phash = hmac.new(secret_key.encode('utf-8'), pstring.encode('utf-8'), hashlib.sha1).hexdigest()
    return phash



def getDepth():
    response = urllib.request.urlopen(BTCC_API_URL['depth'], timeout=1)
    if response.status == 200:
        mybytes = response.read()
        mystr = mybytes.decode("utf8")
        response.close()
        return json.loads(mystr)
    else:
        return False




def request(post_data, apikey, secretkey):
    conn = http.client.HTTPSConnection(BTCC_API_URL['host'])

    # fill in common post_data parameters
    tonce = get_tonce()
    post_data['tonce'] = tonce
    post_data['accesskey'] = apikey
    post_data['requestmethod'] = 'post'

    # If ID is not passed as a key of post_data, just use tonce
    if not 'id' in post_data:
        post_data['id'] = tonce

    pd_hash = get_params_hash(post_data, secretkey)

    # must use b64 encode
    auth_string = 'Basic ' + base64.b64encode((apikey + ':' + pd_hash).encode('utf-8')).decode('utf-8')
    headers = {'Authorization': auth_string, 'Json-Rpc-Tonce': tonce}

    # post_data dictionary passed as JSON
    conn.request("POST", '/api_trade_v1.php', json.dumps(post_data), headers)
    response = conn.getresponse()

    # check response code, ID, and existence of 'result' or 'error'
    # before passing a dict of results
    if response.status == 200:
        # this might fail if non-json data is returned
        resp_dict = json.loads(response.read().decode('utf-8'))
        conn.close()

        # The id's may need to be used by the calling application,
        # but for now, check and discard from the return dict
        if str(resp_dict['id']) == str(post_data['id']):
            if 'result' in resp_dict:
                return resp_dict['result']
            elif 'error' in resp_dict:
                return False
    else:
        conn.close()
        return False

